#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <errno.h>
#include <sys/types.h>
#include <sys/wait.h>

int main()
{
    pid_t id = fork();

    if(id < 0)
    {
        perror("fork");
        exit(1);
    }
    else if(id == 0)
    {
        //子进程
        int cnt = 5;
        while(cnt)
        {
            printf("cnt:%d,我是子进程，pid:%d, ppid:%d\n", cnt, getpid(), getppid());
            sleep(1);
            cnt--;
        }
        exit(121);
    }
    else 
    {
        //父进程
        printf("我是父进程，pid:%d, ppid:%d\n", getpid(), getppid());
        //sleep(7);
        //pid_t ret = wait(NULL);//阻塞式的等待
        int status = 0;
        pid_t ret = waitpid(id, &status, 0);
        if(ret > 0)
        {
            printf("等待子进程成功退出，ret: %d, status: %d\n", ret, (status >> 8) & 0xFF);//次8位为返回信息值
        }
        while(1)
        {
            printf("我是父进程，pid:%d, ppid:%d\n", getpid(), getppid());
            sleep(1);
        }
    }
    return 0;
}
